-- TestScene.lua
-- 测试场景：按F2/F3/F4生成敌人，按ESC返回主菜单

local TestScene = {}
TestScene.__index = TestScene

function TestScene.new(sceneManager, inputManager)
    local instance = setmetatable({
        sceneManager = sceneManager,
        inputManager = inputManager,
        
        scene = nil,
        movementSystem = nil,
        playerEntity = nil,
        playerNode = nil,
        enemySpawner = nil,
        
        -- 测试场景配置
        sceneBounds = {
            left = 0,
            right = 2560,
            top = 1600,
            bottom = 0,
            width = 2560,
            height = 1600
        },
        
        -- 敌人生成位置（固定位置）
        spawnPositions = {
            {x = 500, y = 300},   -- 位置1
            {x = 1000, y = 300},  -- 位置2
            {x = 1500, y = 300},  -- 位置3
            {x = 2000, y = 300}   -- 位置4
        },
        
        currentSpawnIndex = 1,
        
        debugMode = true
    }, TestScene)
    
    return instance
end

-- 创建测试场景
function TestScene:create()
    -- 创建场景
    local Platformer = require("Platformer")
    local scene = Platformer.PlatformWorld()
    self.scene = scene
    
    -- 设置背景（使用图片1.png）
    local Sprite = require("Sprite")
    local bg = Sprite("Image/1.png")
    if bg then
        bg.x = self.sceneBounds.width / 2
        bg.y = self.sceneBounds.height / 2
        scene:addChild(bg)
    end
    
    -- 创建运动系统
    local MovementSystem = require("movement_system")
    local KeyboardInput = require("keyboard_input")
    local keyboardInput = KeyboardInput.new()
    
    self.movementSystem = MovementSystem.new(
        self.sceneBounds.width,
        self.sceneBounds.height,
        self.sceneBounds,
        keyboardInput
    )
    
    -- 添加地面平台
    local groundPlatform = {
        x = 0,
        y = 200,
        width = self.sceneBounds.width,
        height = 50
    }
    self.movementSystem:addGroundPlatform(groundPlatform)
    
    -- 创建玩家（在最左端生成）
    local startPos = {x = 100, y = 300}
    
    -- 创建玩家实体
    local playerEntityData = {
        id = "player",
        position = {x = startPos.x, y = startPos.y},
        velocity = {x = 0, y = 0},
        maxSpeed = 400,
        mass = 1,
        radius = 12.5,  -- 原来的十分之一
        health = 200,
        maxHealth = 200,
        isAlive = true,
        moveInput = 0,
        facingDirection = 1
    }
    
    local success = self.movementSystem:registerEntity(playerEntityData)
    if not success then
        print("错误：注册玩家到运动系统失败")
        return scene
    end
    
    self.playerEntity = self.movementSystem:getEntity("player")
    
    -- 创建玩家节点
    local Node = require("Node")
    self.playerNode = Node()
    self.playerNode.x = startPos.x
    self.playerNode.y = startPos.y
    scene:addChild(self.playerNode)
    
    -- 创建玩家Spine（缩小到十分之一）
    local Spine = require("Spine")
    local playerSpine = Spine("model/que/que")
    if playerSpine then
        playerSpine.scaleX = 0.02  -- 原来的十分之一
        playerSpine.scaleY = 0.02
        playerSpine:play("chi/chi-idle", true)
        self.playerNode:addChild(playerSpine)
    end
    
    -- 创建敌人生成器
    local EnemySpawner = require("EnemySpawner")
    self.enemySpawner = EnemySpawner.new(scene, self.movementSystem, self.playerEntity)
    
    -- 注册键盘输入
    keyboardInput:registerToScene(scene)
    
    -- 设置键盘回调
    self:_setupKeyboardCallbacks(keyboardInput)
    
    -- 注册更新循环
    scene:schedule(function(dt)
        self:update(dt)
    end)
    
    print("测试场景创建完成")
    print("按F2生成剑士，F3生成弓箭手，F4生成刀兵")
    print("按ESC返回主菜单")
    
    return scene
end

-- 设置键盘回调
function TestScene:_setupKeyboardCallbacks(keyboardInput)
    if not keyboardInput then return end
    
    -- F1: 重新加载测试场景（已由主菜单处理）
    -- F2: 生成剑士
    keyboardInput:onKeyPressed("F2", function()
        self:spawnEnemy("sword")
    end)
    
    -- F3: 生成弓箭手
    keyboardInput:onKeyPressed("F3", function()
        self:spawnEnemy("archer")
    end)
    
    -- F4: 生成刀兵
    keyboardInput:onKeyPressed("F4", function()
        self:spawnEnemy("broadsword")
    end)
    
    -- ESC: 返回主菜单
    keyboardInput:onKeyPressed("Escape", function()
        self:returnToMainMenu()
    end)
    
    -- 方向键控制玩家移动
    keyboardInput:onKeyPressed("A", function()
        if self.playerEntity then
            self.playerEntity.moveInput = -1
        end
    end)
    
    keyboardInput:onKeyReleased("A", function()
        if self.playerEntity and self.playerEntity.moveInput == -1 then
            self.playerEntity.moveInput = 0
        end
    end)
    
    keyboardInput:onKeyPressed("D", function()
        if self.playerEntity then
            self.playerEntity.moveInput = 1
        end
    end)
    
    keyboardInput:onKeyReleased("D", function()
        if self.playerEntity and self.playerEntity.moveInput == 1 then
            self.playerEntity.moveInput = 0
        end
    end)
    
    -- 空格键跳跃
    keyboardInput:onKeyPressed("Space", function()
        if self.playerEntity and self.playerEntity.isGrounded then
            self.playerEntity.velocity.y = 500  -- 跳跃力
        end
    end)
end

-- 生成敌人
function TestScene:spawnEnemy(enemyType)
    if not self.enemySpawner then return end
    
    -- 获取下一个生成位置
    local spawnPos = self.spawnPositions[self.currentSpawnIndex]
    if not spawnPos then
        self.currentSpawnIndex = 1
        spawnPos = self.spawnPositions[1]
    end
    
    -- 生成敌人
    local enemy = self.enemySpawner:spawnEnemy(enemyType, spawnPos)
    
    if enemy then
        print(string.format("生成%s敌人，位置: (%d, %d)", 
            enemyType, spawnPos.x, spawnPos.y))
        
        -- 更新生成位置索引
        self.currentSpawnIndex = self.currentSpawnIndex + 1
        if self.currentSpawnIndex > #self.spawnPositions then
            self.currentSpawnIndex = 1
        end
    end
end

-- 更新测试场景
function TestScene:update(dt)
    -- 更新运动系统
    if self.movementSystem then
        self.movementSystem:update(dt)
        
        -- 更新玩家节点位置
        if self.playerEntity then
            local entity = self.movementSystem:getEntity("player")
            if entity then
                self.playerNode.x = entity.position.x
                self.playerNode.y = entity.position.y
                
                -- 更新玩家实体数据
                self.playerEntity.position.x = entity.position.x
                self.playerEntity.position.y = entity.position.y
                self.playerEntity.velocity.x = entity.velocity.x
                self.playerEntity.velocity.y = entity.velocity.y
                self.playerEntity.isGrounded = entity.isGrounded
                self.playerEntity.facingDirection = entity.lastDirection
            end
        end
    end
    
    -- 更新敌人
    if self.enemySpawner then
        self.enemySpawner:update(dt)
    end
    
    -- 边界检查
    if self.playerEntity then
        self:_checkBoundaries()
    end
end

-- 边界检查
function TestScene:_checkBoundaries()
    local pos = self.playerEntity.position
    
    -- X轴边界
    if pos.x < 0 then
        pos.x = 0
        self.playerEntity.velocity.x = 0
    elseif pos.x > self.sceneBounds.width then
        pos.x = self.sceneBounds.width
        self.playerEntity.velocity.x = 0
    end
    
    -- Y轴边界（防止掉出场景）
    if pos.y < -100 then
        pos.y = 300  -- 重置到初始高度
        pos.x = 100
        self.playerEntity.velocity.x = 0
        self.playerEntity.velocity.y = 0
    end
end

-- 返回主菜单
function TestScene:returnToMainMenu()
    if self.sceneManager then
        -- 清理测试场景
        self:cleanup()
        
        -- 切换回主菜单
        self.sceneManager:switchToScene("MainMenu")
    end
end

-- 清理资源
function TestScene:cleanup()
    -- 清理敌人生成器
    if self.enemySpawner then
        self.enemySpawner:cleanup()
        self.enemySpawner = nil
    end
    
    -- 清理运动系统
    if self.movementSystem then
        self.movementSystem:reset()
        self.movementSystem = nil
    end
    
    -- 清理玩家节点
    if self.playerNode and self.playerNode.parent then
        self.playerNode:removeFromParent()
    end
    
    self.playerEntity = nil
    self.playerNode = nil
    self.scene = nil
    
    print("测试场景清理完成")
end

return TestScene